<?php

declare (strict_types=1);

namespace app\api\controller;

use Dengje\Pxy\BaseController;

class Controller extends BaseController
{
    protected array $middleware = ['api'];

    /**
     * 获取用户Token与基本信息
     * @param array $param 参数类型参数名参数作用
     * @return json|array
     * @throws \AlibabaCloud|Client|Result|array
     */
    public function getToken($mobile = '')
    {
        $url = 'http://pbs.chaopin100.com/api/emp/user/phoneAccess';
        $data = ['phone' => $mobile ?: '18049022070'];
        try {
            $result = $this->httpPost($url, $data);
            if ($result['code'] != 200) {
                throw new \Exception($result['msg']);
            }
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
        return $result['data'];
    }

    /**
     * 发送HTTP POST请求
     * @param string $url 请求地址
     * @param array $data 请求数据
     * @return array
     */
    protected function httpPost($url, $data)
    {
        $jsonData = json_encode($data);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'Content-Length: ' . strlen($jsonData)
        ]);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $response = curl_exec($ch);

        if ($response === false) {
            throw new \RuntimeException('请求失败: ' . curl_error($ch));
        }

        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        $result = json_decode($response, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new \RuntimeException('JSON解析失败: ' . json_last_error_msg());
        }

        return $result;
    }
}